#-*-encoding=utf-8-*-
@script_attr(permission='zope.View',use_template='basic')
def total_days_modify():
    """Financial settings

None"""

    msg_list = [u"All user's total day updated",
               ]
    
    #判断是否有权限
    if 'financial' not in call_script('can_access',request = request):
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
    
    if request.method == "POST":
        user_table = context['user_info']
        for one_user in user_table.values():
            one_user = IFieldStorage(one_user)
            
            value = str2float(request.get(one_user['username'], -1))
            
            #表单中不存在该用户数据，不修改
            if not value:
                continue
            one_user['total_days'] = value
    
        #在user_table中不存在的用户
        user_table = context['user_info']
        for key, value in request.form.items():
            if isinstance(value,list):
                value, type = value
                if type == u'new':
                    data = {}
                    data['username'] = key
                    data['first_name'] = u''
                    data['last_name'] = u''
                    data['CN_name'] = u''
                    data['total_days'] = str2float(value)
                    user_table.addRow(data)
        appletsetting['financials_status'] = u'Submitted'
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.total_days_modify?msg_id=0')
    
    else:
        msg = int(request.get('msg_id', -1))
        if msg == -1:
            msg = None
        else:
            msg = msg_list[msg]
    
        user_count = 0
        #查询当前部门信息
        #这里为了提高查询速度，先建立一个user<->section的dict
        section_table = appletsetting['sections']
        sec_user_dict = {}
        total_days = {}
        for one_sec in section_table:
            sec_user_dict.update(dict.fromkeys(one_sec['employees'], one_sec['sec_name']))
            total_days[one_sec['sec_name']] = dict.fromkeys(one_sec['employees'], None)
            user_count = user_count + len(one_sec['employees'])
            
        user_table = context['user_info']
    
        #total_days的格式是section_name->(user_name->user_object)
        for key, one_user in user_table.items():
            one_user = IFieldStorage(one_user)
            user_section = sec_user_dict.get(one_user['username'], None)
            #用户不再任何部门里，残留用户，删除之
            if user_section == None:
                del user_table[key]
                continue
    
            if user_section not in total_days:
                total_days[user_section] = {}
            total_days[user_section][one_user['username']] = one_user
        month = appletsetting['month']
        status = appletsetting['financials_status']
        return render_template('total_days_modify_pt',
                                msg = msg,
                                status = status,
                                user_count = user_count,
                                month = month,
                                total_days = total_days)
    

@script_attr(permission=u'zope.View',use_template='basic')
def index():
    """Index

None"""
    allow = call_script('can_access', request = request, context = context)
    if not allow:
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
    if 'my_timesheet' in allow:
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet')
    elif 'company_summary' in allow:
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.company_summary')
    elif 'financial' in allow:
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.total_days_modify')
    #如果全部都不行，就是部门的权限
    else:
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.section_summary?sec_name=%s' % allow[0])

@script_attr(permission='zope.View',use_template='basic')
def getUserInfo():
    """None

None"""

    user_table = context['user_info']
    user_info = user_table.queryRows().values()
    result = {}
    
    if not user_info:
        return {}
    
    for one_row in user_info:
        one_row = IFieldStorage(one_row)
        result[one_row['username']] = dict(one_row.items())
    
    
    return result
    

@script_attr(permission=u'zope.View',use_template='none')
def getCompanyTimeSheet():
    """getCompanyTimeSheet

Internal API,used for getting total timesheet summary"""

    section_table = appletsetting['sections']
    sections = ITinyTable(section_table).queryRows()
    prj_list = context['projects'].queryRows(as_storage = True).values()
    #连接other_list
    other_list = appletsetting['others']
    prj_list.extend( [{'project_name': other_name} for other_name in other_list] )
    result = {}
    result['totals'] = {}
    all_totals = 0.0
    for one_sec in sections:
        #获取某个部门的汇总
        sec_name = one_sec['sec_name']
        sec_ts_sum = call_script('getSectionTimesheet',section_name = sec_name, context=context)
    
        for one_prj in prj_list:
            prj_name = one_prj['project_name']
            if prj_name not in result:
                result[prj_name] = {}
                result[prj_name]['totals'] = 0.0
            result[prj_name][sec_name] = sec_ts_sum[prj_name]['totals']
            #这里是统计每一项工程，所有部门的时
            if one_sec['status'] == u'Confirmed':
                #只统计已经确认的部门
                result[prj_name]['totals'] = result[prj_name]['totals'] + sec_ts_sum[prj_name]['totals']
        result['totals'][sec_name] = sec_ts_sum['totals']['totals']
        if one_sec['status'] == u'Confirmed':
            #只统计已经确认的部门
            all_totals = all_totals + sec_ts_sum['totals']['totals']
    
    result['totals']['totals'] = all_totals
    return result
    

@script_attr(permission=u'zope.View',use_template='none')
def getNav():
    """Get nav menu code

None"""

    #渲染导航菜单
    section_table = appletsetting['sections']
    sections = ITinyTable(section_table).queryRows()
    allow_access = call_script(u'can_access', request = request)
    try:
        nav = render_template('nav_template', allow = allow_access, sections = sections, selected = selected,sec_name=sec_name)
    except NameError:
        nav = render_template('nav_template', allow = allow_access, sections = sections, selected = selected)
    return nav
    

@script_attr(permission='zope.View',use_template='none')
def getUserDeptStatus():
    """None

Return the gaven user's department status"""

    #查询所有表格
    section_table = appletsetting['sections']
    for one_sec in section_table:
        if user in one_sec['employees']:
            return (one_sec['status'],one_sec['sec_name'])
        
    return []
    

@script_attr(permission='zope.View',use_template='none')
def newTimesheet():
    """None

Start a new timesheet"""

    final_status = appletsetting['status']
    if not checkPermission('zope.ManageContent', context):
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
    if final_status != u'Confirmed':
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=1')
    #删除Timesheet中的所有行
    timesheet_table = context['timesheet']
    timesheet_table.delRows()
    #清除各部门的确认状态
    section_table = appletsetting['sections']
    for one_sec in section_table:
        one_sec['status'] = u'Initial'
    appletsetting['status'] = u'Initial'
    
    #清除用户的状态
    user_table = context['user_table']
    user_table.updateRows({'status': None, 'total_days': None})
    
    #设定新的月份
    appletsetting['month'] = datetime.datetime.today().strftime("%b, %y")
    appletsetting['financials_status'] = u'UnSubmitted'
    return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=2')
    

@script_attr(permission=u'zope.View',use_template='none')
def setup():
    """Setup

None"""

    app_container = deployApplet(package, context)
    IAppletData(app_container).tabpages.append('code:index')
    deployApplet('default.superapplet', app_container,'projects', 'Project manager')
    deployApplet('default.superapplet', app_container,'user_info', 'User manager')
    deployApplet('default.superapplet', app_container,'timesheet', 'Timesheet manager')
    
    deployDataManager(app_container,'add_prj', 'Add project', 'zopen.timesheet.nw_prj','zopen.timesheet.nw_prj')
    deployDataManager(app_container,'del_prj', 'Remove project', 'zopen.timesheet.rm_prj','zopen.timesheet.rm_prj')
    
    IAppletData(app_container).tabpages.append('code:total_days_modify')
    
    IStatusMessage(request).add('Deploy timesheet applet success!You need to configure this timesheet applet and Add Project flow!', 'info')
    return request.response.redirect(absoluteURL(app_container, request) + '/@@applet_property')

@script_attr(permission='zope.View',use_template='none')
def confirm():
    """None

None"""

    #TODO
    #这里还需要检查一下权限
    which = request.get('which',None)
    if not which:
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
    if which == 'section':
        section_name = request.get('sec_name',None)
        sec_tab = appletsetting['sections']
        target_section = ITinyTable(sec_tab).queryOneRow(sec_name = section_name)
        target_section['status'] = u'Confirmed'
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.section_summary?msg_id=0&sec_name=%s' % section_name)
    elif which == 'company':
        appletsetting['status'] = u'Confirmed'
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.company_summary?msg_id=0')
    

@script_attr(permission='zope.View',use_template='none')
def can_access():
    """Can acess module

return Bool"""

    result = []
    viewers = appletsetting['viewers']
    general_manager = appletsetting['general_manager']
    financial_persons = appletsetting['financials']
    
    all_user_list = call_script('getAllUserList')
    cur_user = request.principal.id
    view_all = False
    confirm_all = False
    #如果是my_timesheet模块的话，就只检查是否在列表中
    if cur_user in all_user_list:
        result.append('timesheet')
        result.append('my_timesheet')
    
    #管理人员
    if checkPermission('zope.ManageContent', applet):
        result.append('newtimesheet')
        result.append('financial')
        result.append('property_set')
        result.append('settings')
        view_all = True
        confirm_all = True
    
    if cur_user == general_manager:
        result.append('newtimesheet')
        result.append('financial')
        result.append('settings')
        view_all = True
        confirm_all = True
    
    if cur_user in viewers:
        view_all = True
    
    if view_all:
        result.append('timesheet')
        result.append('company_summary')
    
    if confirm_all:
        result.append('final_confirm')
    
    #检查部门经理
    sections = appletsetting['sections']
    for one_sec in sections:
        if view_all or cur_user == one_sec['manager']:
            result.append(one_sec['sec_name'])
            result.append('timesheet')
        if cur_user == one_sec['manager'] or confirm_all:
            result.append("confirm_%s" % one_sec['sec_name'])
            result.append('timesheet')
    
    #检查财务人员
    if cur_user in financial_persons:
        result.append('financial')
        result.append('settings')
    
    return result
    

@script_attr(permission=u'zope.View',use_template='basic')
def my_timesheet():
    """Timesheet

View My timesheet"""

    msg_list = [u'更新TimeSheet成功',
                u'用户信息添加成功',
                u'更新失败，超过了规定的总天数',
                u'请先初始化项目列表',
                u'部门经理已经确认，不能修改',
                u'用户信息修改成功',
               ]
    nav = call_script('getNav',selected = 'my_timesheet', request = request)
    #判断是否有权限
    if 'my_timesheet' not in call_script('can_access',request = request):
        return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
    
    if request.method == 'POST':
        #如果是添加用户信息的
        if request.get('add_info',None):
            user_tb = context['user_info']
            data = {}
            data['username'] = request.principal.id
            data['first_name'] = request.get('first_name', None)
            data['last_name'] = request.get('last_name', None)
            data['CN_name'] = request.get('CN_name', None)
            data['total_days'] = None
            user_tb.addRow(data)
            return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet?msg_id=1')
    
        #修改用户信息
        elif request.get('edit_info',None):
            user_table = context['user_info']
            user_data = IFieldStorage(user_table.queryOneRow(username=request.principal.id))
            user_data['first_name'] = request.get('first_name', None)
            user_data['last_name'] = request.get('last_name', None)
            user_data['CN_name'] = request.get('CN_name', None)
            return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet?msg_id=5')
    
        #添加timesheet的
        else:
            #检查是否已经确认
            status,dept = call_script('getUserDeptStatus',user = request.principal.id)
            if status == 'Confirmed':
                return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet?msg_id=4')
    
            timesheet_tb = context['timesheet']
            #循环每一个表单变量
            #表单变量的key是name,value是一个list,包含对应的分类和天数
            data = {}
            #检查是否超出规定的日期数
            total = 0.0
            for key,value in request.form.items():
                value[1] = str2float(value[1])
                total = total + value[1]
            user_tb = context['user_info']
            data = IFieldStorage(user_tb.queryOneRow(username = request.principal.id))
            if total > data['total_days']:
                return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet?msg_id=2')
                
            for key,value in request.form.items():
                if not (value[1] and value[1]):#如果是空或者
                    continue
                data['username'] = request.principal.id
                data['belong_name'] = key
                data['belong_type'] = value[0]
                data['days'] = value[1]
                #XXX 数据库中不保存days=0.0的数据
                #  添加时，先检查是否存在该行，如不存在，添加，如存在，更新
                result = timesheet_tb.queryOneRow(username=data['username'],
                                                  belong_name=data['belong_name'],
                                                  belong_type = data['belong_type'],)
                if not result:
                    timesheet_tb.addRow(data)
                else:
                    result = IFieldStorage(result)
                    result['days'] = data['days']
            data['status'] = u'Submitted'
            return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet?msg_id=0')
    else:
        user_name = request.principal.id
        #查询系统用户数
        user_id_list = call_script('getAllUserList')
        user_count = len(user_id_list)
        msg = int(request.get('msg_id',-1))
        if msg == -1:
            msg = None
        else:
            msg = msg_list[msg]
    
        #查询用户的部门和对应的状态
        status,dept = call_script('getUserDeptStatus',user = user_name)
        #查询所有的项目
        prj_lst = call_script('getProjectList', context = context)
        #如果没有prj_lst的话
        if not prj_lst:
            return request.response.redirect(absoluteURL(context,request) + '/++script++zopen.timesheet.my_timesheet?msg_id=3')
    
        #查询用户信息
        #TODO如果没有这个用户，则出错
        user_row = context['user_info'].queryOneRow(username = user_name)
        if user_row:
            user_info = IFieldStorage(user_row)
        else:
            user_info = None
            
        #查询timesheet信息
        timesheet_info = context['timesheet'].queryRows(as_storage = True, 
                                                              username = request.principal.id)
        #创建一个默认的Timesheet，所有的值都为0
        timesheet_info_tmp = dict( [(x, 
                                        dict( [(z['project_name'], None) for z in y]) )
                                            for x, y in prj_lst.items()] )
    
        for x in timesheet_info.values():
                timesheet_info_tmp[x['belong_type']][x['belong_name']] = x['days']
    
        month = appletsetting['month']
    
        return render_template('my_timesheet_pt',
                                prj_lst = prj_lst,
                                nav = nav,
                                personal_info = user_info,
                                ts_info = timesheet_info_tmp,
                                user_count = user_count,
                                msg = msg,
                                month = month,
                                status = status,
                                dept = dept) 
    

@script_attr(permission=u'zope.View',use_template='none')
def getProjectList():
    """InternalAPI,get project list

Get Project list api"""

    project_info = {}
    
    data_items = context['projects']
    
    for key, value in data_items.items():
        storage = IFieldStorage(value)
        categories = storage['categories']
        if categories not in project_info:
            project_info[categories] = []
        projects = project_info[categories]
        projects.append(dict(storage.items()))
    
    #查询Other列表
    other_lst = appletsetting['others']
    project_info['other'] = [ {'project_name': other_name} for other_name in other_lst]
    return project_info
    

@script_attr(permission='zope.View',use_template='basic')
def error_msg():
    """None

None"""

    msg_list = [u'You are not authority to view this page',
                u'Can not start a new timesheet, general manager did not confirmed.',
                u'Start new timesheet successfully'
               ]
    msg_id = str2int(request.get('msg_id', -1))
    if msg_id == -1:
        return "URL错误"
    else:
        nav = call_script('getNav',selected = None, context = context, request=request)
        msg = msg_list[msg_id]
        return render_template('error_template',
                        msg = msg,
                        nav = nav)
    

@script_attr(permission='zope.Public',use_template='none')
def export_xls():
    """Export to CSV file

Export data to an excel file"""

    result = StringIO.StringIO()
    wbook = xlwt.Workbook()
    
    type = request.get('type', None)
    section_name = request.get('sec_name', None)
    date = appletsetting['month']
    if type == 'total':
        ws = wbook.add_sheet("Total")
        #Section list
        property_sheet = appletsetting
        section_table = property_sheet['sections']
        sections = ITinyTable(section_table).queryRows()
        sec_names = [(x['sec_name'],x['status']) for x in sections]
        prj_lst = call_script('getProjectList', context = context)#Project list
        company_sum = call_script('getCompanyTimeSheet', context = context)
        user_info = call_script('getUserInfo', context=context)
        cur_row = 0
        cur_col =0
        ws.write(cur_row, 0, "Sagem Timesheet, %s" % date)
        cur_row = cur_row + 1
        ws.write(cur_row, cur_col + 0, "Project")
        ws.write(cur_row, cur_col + 1, "SZNOrder")
        ws.write(cur_row, cur_col + 2, "Command NO.")
        ws.write(cur_row, cur_col + 3, "IPDE")
        ws.write(cur_row, cur_col + 4, "Total")
        cur_col = cur_col + 5   
        for one_sec_name in sec_names:
            ws.write(cur_row, cur_col, one_sec_name[0])
            cur_col = cur_col + 1
        cur_row = cur_row + 1
        cur_col = 0
    
        for key, value in prj_lst.items():
            if key != u'other':
                ws.write(cur_row, cur_col, key)
                cur_row = cur_row + 1            
                for one_prj in value:
                    ws.write(cur_row, cur_col + 0, one_prj['project_name'])
                    ws.write(cur_row, cur_col + 1, one_prj['szn_order'])
                    ws.write(cur_row, cur_col + 2, one_prj['command'])
                    ws.write(cur_row, cur_col + 3, one_prj['ipde'])
                    cur_col = cur_col + 4
                    ws.write(cur_row, cur_col, company_sum[one_prj['project_name']]['totals'])
                    cur_col = cur_col + 1
                    for one_sec_name in sec_names:
                        ws.write(cur_row, cur_col, company_sum[one_prj['project_name']][one_sec_name[0]])
                        cur_col = cur_col + 1
                    cur_row = cur_row + 1
                    cur_col = 0
                
        if u'other' in prj_lst:
            key = u'other'
            value = prj_lst[key]
            ws.write(cur_row, cur_col, u'OTHER')
            cur_row = cur_row + 1
            for one_prj in value:
                ws.write(cur_row, cur_col + 0, one_prj['project_name'])
                cur_col = cur_col + 4
                ws.write(cur_row, cur_col, company_sum[one_prj['project_name']]['totals'])
                cur_col = cur_col + 1
                for one_sec_name in sec_names:
                    ws.write(cur_row, cur_col, company_sum[one_prj['project_name']][one_sec_name[0]])
                    cur_col = cur_col + 1
                cur_row = cur_row + 1
                cur_col = 0
        
        ws.write(cur_row, cur_col, u'TOTAL')
        cur_row = cur_row + 1
        cur_col = cur_col + 4
        ws.write(cur_row, cur_col, company_sum['totals']['totals'])
        cur_col = cur_col + 1
        for one_sec_name in sec_names:
            ws.write(cur_row, cur_col, company_sum['totals'][one_sec_name[0]])
            cur_col = cur_col + 1
        
        for one_sec in sections:
            ws = wbook.add_sheet(one_sec['sec_name'])
            sec_sum = call_script('getSectionTimesheet',section_name = one_sec['sec_name'], context=context)
            cur_row = 0
            cur_col =0
            ws.write(cur_row, 0, "Sagem Timesheet,%s , Sections:%s" % (date, one_sec['sec_name']))
            cur_row = cur_row + 1
            ws.write(cur_row, cur_col + 0, "Project")
            ws.write(cur_row, cur_col + 1, "SZNOrder")
            ws.write(cur_row, cur_col + 2, "Command NO.")
            ws.write(cur_row, cur_col + 3, "IPDE")
            ws.write(cur_row, cur_col + 4, "Total")
            cur_col = cur_col + 5           
            for one_emp in one_sec['employees']:
                one_user_info = user_info.get(one_emp, None)
                if one_user_info == None or \
                   not(one_user_info.get('first_name', None) or \
                   one_user_info.get('last_name', None) or \
                   one_user_info.get('CN_name', None)):
                   ws.write(cur_row, cur_col, one_emp.rsplit('.', 1)[1])
                   cur_col = cur_col + 1
                else:
                   ws.write(cur_row, cur_col, 
                            "%s\n%s\n%s" % (one_user_info.get('first_name', None),
                                            one_user_info.get('last_name', None),
                                            one_user_info.get('CN_name', None)))
                   cur_col = cur_col + 1
            cur_row = cur_row + 1
            cur_col = 0   
            for key, value in prj_lst.items():
                if key != u'other':
                    ws.write(cur_row, cur_col, key)
                    cur_row = cur_row + 1
                    for one_prj in value:
                        ws.write(cur_row, cur_col + 0, one_prj['project_name'])
                        ws.write(cur_row, cur_col + 1, one_prj['szn_order'])
                        ws.write(cur_row, cur_col + 2, one_prj['command'])
                        ws.write(cur_row, cur_col + 3, one_prj['ipde'])
                        cur_col = cur_col + 4
                        ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']]['totals'])
                        cur_col = cur_col + 1
                        for one_emp in one_sec['employees']:
                            ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']].get(one_emp, None))
                            cur_col = cur_col + 1
                        cur_row = cur_row + 1
                        cur_col = 0  
            if u'other' in prj_lst:
                key = u'other'
                value = prj_lst[key]
                ws.write(cur_row, cur_col, u'OTHER')
                cur_row = cur_row + 1
                for one_prj in value:
                    ws.write(cur_row, cur_col + 0, one_prj['project_name'])
                    cur_col = cur_col + 4
                    ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']]['totals'])
                    cur_col = cur_col + 1
                    for one_emp in one_sec['employees']:
                        ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']].get(one_emp, None))
                        cur_col = cur_col + 1
                    cur_row = cur_row + 1
                    cur_col = 0
                    
            ws.write(cur_row, cur_col, u'TOTAL')
            cur_row = cur_row + 1
            cur_col = cur_col + 4
            ws.write(cur_row, cur_col, sec_sum['totals'].get('totals', None))
            cur_col = cur_col + 1
            for one_emp in one_sec['employees']:
                ws.write(cur_row, cur_col, sec_sum['totals'].get(one_emp, None))
                cur_col = cur_col + 1                
        filename = 'Total-Timesheet.xls'
    elif type == u'section':
        property_sheet = appletsetting
        section_table = property_sheet['sections']
        one_sec = ITinyTable(section_table).queryOneRow(sec_name = section_name)
        prj_lst = call_script('getProjectList', context=context)#Project list
        user_info = call_script('getUserInfo', context=context)
        
        ws = wbook.add_sheet(one_sec['sec_name'])
        sec_sum = call_script('getSectionTimesheet',section_name = one_sec['sec_name'], context=context)
        cur_row = 0
        cur_col = 0
        ws.write(cur_row, 0, "Sagem Timesheet, %s, Sections:%s" % (date, one_sec['sec_name']))
        cur_row = cur_row + 1
        ws.write(cur_row, cur_col + 0, "Project")
        ws.write(cur_row, cur_col + 1, "SZNOrder")
        ws.write(cur_row, cur_col + 2, "Command NO.")
        ws.write(cur_row, cur_col + 3, "IPDE")
        ws.write(cur_row, cur_col + 4, "Total")
        cur_col = cur_col + 5           
        for one_emp in one_sec['employees']:
            one_user_info = user_info.get(one_emp, None)
            if one_user_info == None or \
               not(one_user_info.get('first_name', None) or \
               one_user_info.get('last_name', None) or \
               one_user_info.get('CN_name', None)):
               ws.write(cur_row, cur_col, one_emp.rsplit('.', 1)[1])
               cur_col = cur_col + 1
            else:
               ws.write(cur_row, cur_col, 
                        "%s\n%s\n%s" % (one_user_info.get('first_name', None),
                                        one_user_info.get('last_name', None),
                                        one_user_info.get('CN_name', None)))
               cur_col = cur_col + 1
        cur_row = cur_row + 1
        cur_col = 0   
        for key, value in prj_lst.items():
            if key != u'other':
                ws.write(cur_row, cur_col, key)
                cur_row = cur_row + 1
                for one_prj in value:
                    ws.write(cur_row, cur_col + 0, one_prj['project_name'])
                    ws.write(cur_row, cur_col + 1, one_prj['szn_order'])
                    ws.write(cur_row, cur_col + 2, one_prj['command'])
                    ws.write(cur_row, cur_col + 3, one_prj['ipde'])
                    cur_col = cur_col + 4
                    ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']]['totals'])
                    cur_col = cur_col + 1
                    for one_emp in one_sec['employees']:
                        ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']].get(one_emp, None))
                        cur_col = cur_col + 1
                    cur_row = cur_row + 1
                    cur_col = 0  
        if u'other' in prj_lst:
            key = u'other'
            value = prj_lst[key]
            ws.write(cur_row, cur_col, u'OTHER')
            cur_row = cur_row + 1
            for one_prj in value:
                ws.write(cur_row, cur_col + 0, one_prj['project_name'])
                cur_col = cur_col + 4
                ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']]['totals'])
                cur_col = cur_col + 1
                for one_emp in one_sec['employees']:
                    ws.write(cur_row, cur_col, sec_sum[one_prj['project_name']].get(one_emp, None))
                    cur_col = cur_col + 1
                cur_row = cur_row + 1
                cur_col = 0
                
            ws.write(cur_row, cur_col, u'TOTAL')
            cur_row = cur_row + 1
            cur_col = cur_col + 4
            ws.write(cur_row, cur_col, sec_sum['totals'].get('totals', None))
            cur_col = cur_col + 1
            for one_emp in one_sec['employees']:
                ws.write(cur_row, cur_col, sec_sum['totals'].get(one_emp, None))
                cur_col = cur_col + 1
        filename = '%s-Timesheet.xls' % section_name
    
    wbook.save(result)
    #Set header
    request.response.setHeader('Content-Type', 'application/excel')
    request.response.setHeader('Content-Disposition', 'attachment; filename=%s' % filename)
    
    result.seek(0)
    return result.read()
    

@script_attr(permission='zope.View',use_template='none')
def getAllUserList():
    """Get User List

This script is used to get all user list(id)"""

    sections = appletsetting['sections']
    result = []
    for one_row in sections:
        result.extend(one_row['employees'])
    #remove same element
    result = list(set(result))
    return result
    

@script_attr(permission=u'zope.View',use_template='basic')
def section_summary():
    """Section timesheet summary

None"""

    msg_list = [u'Timesheet confirm successfully.',
               ]
    section_name = request.get('sec_name',None)
    if section_name:
        #查询当前部门信息
        section_table = appletsetting['sections']
        section = ITinyTable(section_table).queryOneRow(sec_name = section_name)
        #检查权限
        allow = call_script('can_access',request = request)
        if section_name not in allow:
            return request.response.redirect(absoluteURL(app,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
        confirm_str = 'confirm_%s' % section_name
        can_confirm = False
        if confirm_str in allow:
            can_confirm = True
    
        #渲染菜单
        nav = call_script('getNav', selected='section_timesheet', sec_name=section_name, request=request)
        msg = int(request.get('msg_id', -1))
    
        if msg == -1:
            msg = None
        else:
            msg = msg_list[msg]
    
        user_info = call_script('getUserInfo', context = context)
        prj_lst = call_script('getProjectList', context = context)#Project list
        sec_ts = call_script('getSectionTimesheet',section_name = section_name, context = context)
        user_list = section['employees']
        status = section['status']
    
        #查询系统用户数
        user_count = 0
        submitted_count = 0
        unsubmitted_count = 0
        for employee in section['employees']:
            emp_info = user_info.get(employee, None)
            #还没填写用户信息
            if (not emp_info):
                unsubmitted_count + 1
                continue
            user_status = emp_info.get('status', None)
    
            if user_status == u'Submitted':
                submitted_count = submitted_count + 1
            else:
                unsubmitted_count = unsubmitted_count + 1
            user_count = user_count + 1
    
        
        #查询other列表
        other_lst = appletsetting['others']
        month = appletsetting['month']
        general_status = appletsetting['status']
        return render_template('timesheet_section_pt',
                                user_list = user_list,
                                sec_ts = sec_ts,
                                prj_lst = prj_lst,
                                nav = nav,
                                sec_name = section_name,
                                user_count = user_count,
                                submitted_count = submitted_count,
                                unsubmitted_count = unsubmitted_count,
                                msg = msg,
                                status = status,
                                general_status = general_status,
                                user_info = user_info,
                                can_confirm = can_confirm,
                                month = month,
                                other_lst = other_lst)
    else:
        return "URL错误，请输入正确的URL"
    

@script_attr(permission=u'zope.View',use_template='basic')
def getSectionTimesheet():
    """Get section timesheet

None"""

    section_table = appletsetting['sections']
    section = ITinyTable(section_table).queryOneRow(sec_name = section_name)
    timesheet_table = context['timesheet']
    user_list = section.get('employees',[])
    prj_list = context['projects'].queryRows(as_storage=True).values()
    #连接 Other 项
    other_list = appletsetting['others']
    prj_list.extend([ {'project_name': other_name} for other_name in other_list])
    
    all_total = 0.0
    result = {}
    result['totals'] = {}
    for one_prj in prj_list:
        prj_name = one_prj['project_name']
        prj_sum = {}
        total_days = 0.0
        for one_user in user_list:
            data = timesheet_table.queryOneRow(username=one_user, belong_name = prj_name)
            if not data:
                continue
            if one_user not in result['totals']:
                result['totals'][one_user] = 0.0
            storage = IFieldStorage(data)
            days = storage['days']
            #所有相同的工程所有用户的统计
            result['totals'][one_user] = result['totals'][one_user] + days
            #所有用户的相同工程的统计
            prj_sum[one_user] = days    
            total_days = total_days + days
        result[prj_name] = prj_sum
        #prj_sum本来是存放所有用户一个工程的所用的时间的
        #但totals不是一个真正的user，只是一个统计项
        prj_sum['totals'] = total_days
        all_total = all_total + total_days
    #总的统计
    result['totals']['totals'] = all_total
    return result
    

@script_attr(permission=u'zope.View',use_template='basic')
def company_summary():
    """Company's summary timesheet code

None"""

    #检查权限
    allow = call_script('can_access', request = request, context=context)
    if 'company_summary' not in allow:
        return request.response.redirect(absoluteURL(app,request) + '/++script++zopen.timesheet.error_msg?msg_id=0')
    can_confirm = False
    if 'final_confirm' in allow:
        can_confirm = True
    
    msg_list = [u'Final confirm successfully.',
               ]
    
    msg = int(request.get('msg_id', -1))
    if msg == -1:
        msg = None
    else:
        msg = msg_list[msg]
    
    #渲染菜单
    nav = call_script('getNav', selected='company_summary', request=request, context=context)
    
    property_sheet = appletsetting
    
    status = property_sheet['status']
    
    section_table = property_sheet['sections']
    sections = ITinyTable(section_table).queryRows()
    sec_names = [(x['sec_name'],x['status']) for x in sections]
    
    
    confirmed_count = 0
    unconfirmed_count = 0
    for one_sec in sections:
        sec_status = one_sec.get('status', None)
        if sec_status == u'Confirmed':
            confirmed_count = confirmed_count + 1
        else:
            unconfirmed_count = unconfirmed_count + 1
    
    prj_lst = call_script('getProjectList', context=context)#Project list
    
    company_sum = call_script('getCompanyTimeSheet', context=context)
    
    #查询系统用户数
    user_count = len(call_script('getAllUserList', context = context))
    month = appletsetting['month']
    
    return render_template('timesheet_company_pt',
                           sec_names = sec_names,
                           com_ts = company_sum,
                           prj_lst = prj_lst,
                           nav = nav,
                           user_count = user_count,
                           status = status,
                           confirmed_count = confirmed_count,
                           unconfirmed_count = unconfirmed_count,
                           month = month,
                           can_confirm = can_confirm,
                           msg = msg)
    

